import * as fs from 'node:fs/promises';
import * as configuration from '../configuration';
import { log } from '../helper/outputChannel';
import { Memory } from '../memory';
import { addUser } from './addUser';
import { fetchApiList } from './fetchApiList';
import { refreshApi } from './refreshApi';
import * as vscode from 'vscode';
import path = require('node:path');

export namespace RefreshApiTsFilesUnderDir {
  export interface Arg0 {
    fsPath: string;
  }
  export async function call(arg0: Arg0) {
    const dirPath = arg0.fsPath;

    const children = await fs.readdir(dirPath);

    const len = children.length;

    if (!len) {
      return;
    }

    const users = await configuration.getUsers();
    if (!users.length) {
      log.warn('请先添加Torna用户');
      log.show();
      await addUser();
    }

    let docList = Memory.fullDocList.filter(v => v.url);
    if (!docList.length) {
      await fetchApiList();
    }


    for (let i = 0; i < len; ++i) {
      const child = children[i];
      if (!child.endsWith('.ts')) { continue; }

      const childStat = await fs.stat(path.join(dirPath, child));
      if (!childStat.isFile()) { continue; }

      refreshApi({ fsPath: path.join(dirPath, child) });
    }
  }
}
